/**
 * Created by Ding on 2016/4/8.
 * Copyright (c) 2016, auais.com All Rights Reserved.
 * File Name:
 * Package Name:
 * Date:2016/4/8 11:23
 */
const ObjectID = require('mongodb').ObjectID;
const mongo = require('mongodb');
//const GridStore = require('mongodb').GridStore;
const GridFSBucket = require('mongodb').GridFSBucket;
const fs = require("fs");
const path = require('path');
const Grid = require('gridfs-stream');
const Busboy = require('busboy');
const crypto = require('crypto');
const qiniu = require('yi-qiniu');

module.exports = {
    description:'七牛上传',
    handler: (req, res, next)=>{
        req.context=req.context||{};
        const projectId = req.query.projectId;
        const projectName = req.query.projectName;
        const fileType = req.query.fileType;
        const authInfo = req.context.authInfo||{};
        const fsHash = crypto.createHash('md5');
        let filesize = 0;
        let fileData = [];

        const busboy = new Busboy({headers: req.headers});
        req.pipe(busboy);
        busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
            const id = new ObjectID();
            let extName = path.extname(filename);
            let fileName = req.query.fileName || filename;
            if(!path.extname(fileName)||path.extname(fileName)!== extName)
                fileName = fileName + extName;

            file.on('end', function () {

                fileData = Buffer.from(fileData);
                qiniu.uploadBuffer(fileData,fileName,(e,r)=>{
                    if(e)
                    {
                        return res.err.unknownError(e);
                    }
                    const fileObj = {
                        _id: id,
                        filename: filename,
                        content_type: mimetype,
                        filesize: filesize,
                        url: r.url,
                        createTime:new Date(),
                        projectId:projectId,
                        projectName:projectName,
                        fileType:fileType,
                        userId:authInfo._id,
                        userName:authInfo.name,
                        static:2,
                        md5:  fsHash.digest('hex'),
                        hash: r.hash
                    };
                    // res.json(fileObj);
                    res.reply({code:0,message:'上传成功',data:fileObj});
                    //将资源记录用户表
                    let fn = function () {
                    };
                    req.mongo.collection("file").insertOne(fileObj,fn);
                },id.toString());

            }).on('error', function (err) {
                console.log("err:" + err)
                res.reply({code:60001,message:'上传失败：'+err});
            }).on('data', function (data) {
                fileData.push.apply(fileData, data);
                filesize += data.length;
                fsHash.update(data);
            });

        })
    }
};